package com.xtoad.ecms.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xtoad.ecms.common.web.exception.BusinessException;

/**
 * JSON处理辅助类
 *
 * @author xtoad
 * @date 2020/05/29
 */
public class JsonUtils {

    /**
     * 对象转化为Json字符串
     *
     * @param obj 要转化的对象
     * @return json字符串
     */
    public static String stringify(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new BusinessException("-1", "转化Json对象失败");
        }
    }

    /**
     * Json字符串转为对象
     *
     * @param jsonStr json字符串
     * @param type    对象类型
     * @param <T>     泛型
     * @return java对象
     */
    public static <T> T parse(String jsonStr, Class<T> type) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(jsonStr, type);
        } catch (JsonProcessingException e) {
            throw new BusinessException("-1", "解析Json对象失败");
        }
    }
}
